import pandas as pd
import json
# -*- coding: utf-8 -*-
import os
import sys
import redis
import xpinyin

r = redis.Redis(host='localhost', port=6379, decode_responses=True)

pwd = os.path.dirname(os.path.dirname(__file__))

# 进入django设置
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'shop.settings')
import requests
import time
import django

django.setup()

from goods.models import Good, GoodCategory, GoodCarouselImage


def index(content):
    headers = {
        "content-type": "application/json"
    }
    url = 'https://www2.deepl.com/jsonrpc'
    data = {"jsonrpc": "2.0", "method": "LMT_handle_jobs", "params": {"jobs": [
        {"kind": "default", "raw_en_sentence": content, "raw_en_context_before": [],
         "raw_en_context_after": [], "preferred_num_beams": 4}], "lang": {"user_preferred_langs": ["ZH", "EN", "JA"],
                                                                          "source_lang_user_selected": "auto",
                                                                          "target_lang": "ZH"}, "priority": 1,
        "commonJobParams": {"formality": None},
        "timestamp": int(round(time.time() * 1000))}, "id": None}
    count = 5
    while count > 0:
        ip = r.hget('xiaoxiang', 'ip')

        get_ip = json.loads(ip)
        try:
            data = requests.post(url, json=data, headers=headers, proxies=get_ip, timeout=3).json()
            res = data['result']['translations'][0]['beams'][0]['postprocessed_sentence']
            print(res)
        except:
            count -= 1
            continue
        else:
            res = data['result']['translations'][0]['beams'][0]['postprocessed_sentence']
            break

    return res


def get_s(con):
    p = xpinyin.Pinyin()
    result = [p.get_initials(a, '') for a in [con]][0]
    return result


def read():
    # cate1
    df = pd.read_csv(r'F:\japan\FastServer\data\petpochitto.csv')

    for item, row in df.iterrows():
        try:
            category1 = GoodCategory()
            category2 = GoodCategory()
            category3 = GoodCategory()

            # time.sleep(1)
            en_brand = row['en_brand']
            cate1 = index(row['cate1'])
            cate2 = index(row['cate2'])
            cate3 = index(row['cate3'])
            cate1_py = get_s(cate1)
            cate2_py = get_s(cate2)
            cate3_py = get_s(cate3)

            # 一级
            s1 = GoodCategory.objects.filter(name=cate1)
            print(s1, cate1)
            if s1.first():
                category1 = s1.first()
            else:
                category1.name = cate1
                category1.code = cate1_py
                category1.desc = ''
                category1.category_type = 1
                category1.parent_category = None
                category1.save()
            # 二级
            s2 = GoodCategory.objects.filter(name=cate2)
            if s2.first():
                category2 = s2.first()
            else:
                category2.name = cate2
                category2.code = cate2_py
                category2.desc = ''
                category2.category_type = 2
                category2.parent_category = category1
                category2.save()
            # 三级
            s3 = GoodCategory.objects.filter(name=cate3)
            if s3.first():
                category3 = s3.first()
            else:
                category3.name = cate3
                category3.code = cate3_py
                category3.desc = ''
                category3.category_type = 3
                category3.parent_category = category2
                category3.save()

            print(cate1, cate2, cate3, cate1_py, cate2_py, cate3_py)

            # tags = ','.join([index(x) for x in row['tags']])
            tags = row['tags']
            url = row['url']
            j1 = Good.objects.filter(good_url=url)
            if j1.first():
                pass
            else:
                belong = row['belong']
                skus = eval(row['skus'])
                for sku in skus:
                    gd = Good()
                    name = index(sku['name'])
                    brand = sku['brand']

                    market_price = int(sku['market_price']) / 100

                    content = sku['content']
                    description = index(sku['description'])
                    comments = sku['comments']
                    sku_value = sku['sku']
                    status = sku['status']
                    sold_price = int(sku['sold_price']) / 100
                    image = sku['image']
                    rate = sku['rate']

                    gd.category = category3
                    gd.good_sn = sku_value
                    gd.name = name
                    gd.cover = image[0]
                    gd.good_num = 100000
                    gd.sold_num = 0
                    gd.click_num = 0
                    gd.fav_num = 0
                    gd.good_desc = description
                    gd.market_price = market_price
                    gd.shop_price = sold_price
                    gd.good_detail = content
                    gd.is_fare = 0
                    gd.pinpai = en_brand
                    gd.tags = tags
                    gd.good_url = url
                    gd.belong = belong
                    gd.jp_pinpai = brand
                    gd.good_status = status
                    gd.comments = comments
                    gd.rate = rate
                    gd.save()

                    for goods_image in image:
                        print(goods_image)
                        goods_image_instance = GoodCarouselImage()
                        goods_image_instance.image = goods_image
                        goods_image_instance.good = gd
                        goods_image_instance.save()




        except Exception as e:
            with open('add.txt', 'a+', encoding='utf-8') as f:
                f.write(str(row) + '\n')
            print(e)
            continue


if __name__ == '__main__':
    read()
